package com.czy.owner.ui.bottom;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.adapter.CarInformationAdapter;
import com.czy.owner.adapter.FindStrategyAdapter;
import com.czy.owner.adapter.HorizontalActivityAdapter;
import com.czy.owner.api.BannerToFindActivityApi;
import com.czy.owner.api.FindActivityListApi;
import com.czy.owner.api.FindCarInfoApi;
import com.czy.owner.api.StrategyApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.BannerToActivityModel;
import com.czy.owner.entity.FindActivityModel;
import com.czy.owner.entity.FindCarInfoModel;
import com.czy.owner.entity.FindStrategyModel;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.LuckDrawWebviewActivity;
import com.czy.owner.ui.NewWebViewActivity;
import com.czy.owner.ui.WebViewActivity;
import com.czy.owner.ui.information.InformationDetailActivity;
import com.czy.owner.ui.information.RecommendActivityListActivity;
import com.czy.owner.ui.information.StrategyActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.ImageCycleView;
import com.easyrecycleview.EasyRecycleViewUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.easyrecycleview.decoration.SpaceDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.czy.owner.entity.WebViewRequestParam.REQUEST_GET;
import static com.czy.owner.entity.WebViewRequestParam.REQUEST_POST;


/**
 * Created by wangyng on 2017/5/2 0002.
 * 发现
 */

public class FindFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener {

    ImageCycleView headBannerFind;
    EasyRecyclerView recycleViewStrategy;
    @BindView(R.id.recycler_view_news)
    EasyRecyclerView recyclerViewNews;
    private FindStrategyAdapter findStrategyAdapter;
    private CarInformationAdapter carInformationAdapter;//发现页主要适配
    private Handler handler = new Handler();
    private int page = 1;
    private SpaceDecoration itemDecoration;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_find;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        recyclerViewNews.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewNews.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL,
                R.drawable.shape_gray_divider_decoration));
        recyclerViewNews.setAdapter(carInformationAdapter = new CarInformationAdapter(getActivity()));
        carInformationAdapter.setMore(R.layout.view_more, this);
        carInformationAdapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                //findActivityRecommondAdapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                carInformationAdapter.resumeMore();
            }
        });

        carInformationAdapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                carInformationAdapter.resumeMore();

            }

            @Override
            public void onErrorClick() {
                carInformationAdapter.resumeMore();

            }
        });

        carInformationAdapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View view = inflater.inflate(R.layout.find_head_view, null);
                headBannerFind = (ImageCycleView) view.findViewById(R.id.head_banner_find);
                recycleViewStrategy = (EasyRecyclerView) view.findViewById(R.id.recycleview_strategy);
                recyclerViewHeadActivity = (EasyRecyclerView) view.findViewById(R.id.recycler_view_head_activity);
                TextView moreTextBtn = (TextView) view.findViewById(R.id.tv_more_activity);
                initActivityRecyclerView();
                moreTextBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(getActivity(), RecommendActivityListActivity.class);
                        startActivity(i);
                    }
                });
                return view;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });


        /***
         * 获取资讯数据
         */
        getDataList();

        /**
         * 获取顶部ViewPager数据
         */
        getViewPageData();

        /**
         * 获取场景攻略数据
         */
        getStrategyList();

        /**
         * 获取第一页的活动
         */
        getFirstActivityListData();

//        bannerToActivity();

        carInformationAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<FindCarInfoModel>() {
            @Override
            public void onItemClick(View view, int position, FindCarInfoModel model) {
                Intent ti = new Intent(getActivity(), InformationDetailActivity.class);
                ti.putExtra("title", model.getTitle());
                ti.putExtra("content", model.getContent());
                ti.putExtra("imgUrl", model.getCoverUrl());
                ti.putExtra("infoId", model.getInfoId());
                ti.putExtra("isCollect", model.isCollect());
                ti.putExtra("collectType", "carInfo");
                startActivity(ti);
            }
        });


        recyclerViewNews.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                recyclerViewNews.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        carInformationAdapter.clear();
                        page = 1;
                        getDataList();
                        getViewPageData();

                        getStrategyList();
                        getFirstActivityListData();
//                        bannerToActivity();
                    }
                }, 1000);
            }
        });
    }

    /**
     * 获取资讯数据
     */
    private void getDataList() {
        FindCarInfoApi findCarInfoApi = new FindCarInfoApi(new HttpOnNextListener<List<FindCarInfoModel>>() {
            @Override
            public void onNext(List<FindCarInfoModel> list) {
                setDataList(list);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<FindCarInfoModel>>>() {
                }.getType();
                BaseResultEntity<List<FindCarInfoModel>> cacheList = gson.fromJson(cache, type);
                setDataList(cacheList.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(mContext, e.getMessage());
            }
        }, (RxAppCompatActivity) (getContext()), page + "");
        findCarInfoApi.setSession(UserHelper.getInstance().getSession(mContext));
        findCarInfoApi.setPage(page + "");
        findCarInfoApi.setSize("10");
        findCarInfoApi.setTitle("");
        findCarInfoApi.setShowInBanner("false");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(findCarInfoApi);
    }

    private void setDataList(List<FindCarInfoModel> list) {
        if (list.size() < 9) {
            carInformationAdapter.stopMore();
        }
        carInformationAdapter.addAll(list);
        if (carInformationAdapter.getAllData().size() == 0) {
            recyclerViewNews.setEmptyView(R.layout.view_empty_common);
            recyclerViewNews.showEmpty();
        }
    }

    /**========================================活动横向滚动列表=====================================**/
    private EasyRecyclerView recyclerViewHeadActivity;
    private HorizontalActivityAdapter horizontalActivityAdapter;

    /**
     * 初始化活动横向滚动列表
     */
    private void initActivityRecyclerView(){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewHeadActivity.setLayoutManager(linearLayoutManager);
        horizontalActivityAdapter = new HorizontalActivityAdapter(getContext());
        recyclerViewHeadActivity.setAdapter(horizontalActivityAdapter);

        horizontalActivityAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<FindActivityModel>() {
            @Override
            public void onItemClick(View view, int position, FindActivityModel model) {


                if (model.getLinkType().equals("url")) {
                    MyLog.d("RAVEN","url=========="+model.getUrl());
                    if (model.getUrl().contains("own/shop/luckDraw")) {
                        WebViewRequestParam webViewRequestParam = new WebViewRequestParam(Constants.APP_API_BASE + Constants.OWN_SHOP_LUCKDRAW);
                        webViewRequestParam.setRequestMethod(REQUEST_POST);
                        webViewRequestParam.setParams("session=" + UserHelper.getInstance().getSession(getActivity()));
                        webViewRequestParam.setTitle("转盘抽奖");
                        Intent intent = new Intent(getActivity(), LuckDrawWebviewActivity.class);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
                        startActivity(intent);
                    } else if(model.getUrl().contains("/own/shop/doubleEleven")){
                        WebViewRequestParam webViewRequestParam = new WebViewRequestParam(model.getUrl());
                        webViewRequestParam.setRequestMethod(REQUEST_GET);
                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
                        intent.putExtra("type","doubleEleven");
                        intent.putExtra("mFromTypeId",model.getGoodsActivityId()+"");
                        startActivity(intent);
                    }else if(model.getUrl().contains("/own/shop/sunburn")){
                        WebViewRequestParam webViewRequestParam3 = new WebViewRequestParam(Constants.APP_API_BASE + Constants.OWN_SHOP_SUNBURN);
                        webViewRequestParam3.setRequestMethod(REQUEST_GET);
                        webViewRequestParam3.setTitle("晒评价,领现金券");
                        Intent intent3 = new Intent(getActivity(), NewWebViewActivity.class);
                        intent3.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam3);
                        startActivity(intent3);
                    } else if(model.getUrl().contains("own/shop/club")){
                        WebViewRequestParam webViewRequestParam = new WebViewRequestParam(Constants.APP_API_BASE + Constants.OWN_SHOP_CLUB);
                        webViewRequestParam.setRequestMethod(REQUEST_GET);
                        webViewRequestParam.setTitle("FM908");
                        Intent intent1 = new Intent(getActivity(), NewWebViewActivity.class);
                        intent1.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
                        startActivity(intent1);
                    }else if(model.getUrl().contains("own/shop/businessDaily")){
                        WebViewRequestParam webViewRequestParam4 = new WebViewRequestParam(Constants.APP_API_BASE + Constants.OWN_SHOP_BUSINESSDAILY);
                        webViewRequestParam4.setRequestMethod(REQUEST_GET);
                        webViewRequestParam4.setTitle("安徽商报");
                        Intent intent4 = new Intent(getActivity(), NewWebViewActivity.class);
                        intent4.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam4);
                        startActivity(intent4);
                    }else {
                        WebViewRequestParam webViewRequestParam = new WebViewRequestParam(model.getUrl());
                        webViewRequestParam.setRequestMethod(REQUEST_GET);
                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
                        intent.putExtra("type","袋鼠管家");
                        intent.putExtra("mFromTypeId",model.getGoodsActivityId()+"");
                        startActivity(intent);
                        MyLog.e("yang","比价活动");
                    }



                } else {
                    Intent ti = new Intent(getActivity(), InformationDetailActivity.class);
                    ti.putExtra("title", model.getTitle());
                    ti.putExtra("content", model.getDescription1());
                    ti.putExtra("imgUrl", model.getLogo());
                    ti.putExtra("infoId", model.getGoodsActivityId());
                    ti.putExtra("collectType", "activity");
                    startActivity(ti);
                }

            }
        });
    }


    //    推荐banner到活动
    private void bannerToActivity() {

        BannerToFindActivityApi bannerToFindActivityApi = new BannerToFindActivityApi(new HttpOnNextListener<List<BannerToActivityModel>>() {
            @Override
            public void onNext(List<BannerToActivityModel> list) {
                MyLog.e("yang", "list==" + list.size());
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        FindActivityModel model = new FindActivityModel();
                        model.setTitle(list.get(i).getDescription());
                        model.setDescription1(list.get(i).getDescription());
                        model.setLogo(list.get(i).getPicUrl());
                        model.setLinkType(list.get(i).getContactType());
                        model.setUrl(list.get(i).getContactId());
                        horizontalActivityAdapter.add(model);

                    }
                    horizontalActivityAdapter.notifyDataSetChanged();
                }

            }
        }, (RxAppCompatActivity) (getContext()));
        bannerToFindActivityApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(bannerToFindActivityApi);
    }

    /**
     * 获取推荐活动列表
     */
    private void getFirstActivityListData(){

        FindActivityListApi findActivityListApi = new FindActivityListApi(new HttpOnNextListener<List<FindActivityModel>>() {
            @Override
            public void onNext(List<FindActivityModel> list) {
                MyLog.d("RAVEN","getFirstActivityList  size = " + list.size());
                setFirstActivityData(list);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) (getContext()));
        findActivityListApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        findActivityListApi.setPage("1");
        findActivityListApi.setSize("3");
        findActivityListApi.setTitle("");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(findActivityListApi);
    }
    /**
     * 设置活动第一页数据 横向滑动布局展示
     * @param list
     */
    private void setFirstActivityData(List<FindActivityModel> list){
        MyLog.d("RAVEN","setFirstActivityData = " + list.size());
        horizontalActivityAdapter.clear();
        horizontalActivityAdapter.addAll(list);
        horizontalActivityAdapter.notifyDataSetChanged();
    }

    @Override
    protected void updateViews() {

    }

    /**
     * 获取顶部ViewPager数据
     */
    private void getViewPageData() {
        FindCarInfoApi findCarInfoApi = new FindCarInfoApi(new HttpOnNextListener<List<FindCarInfoModel>>() {
            @Override
            public void onNext(List<FindCarInfoModel> list) {
                setViewPageData(list);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<FindCarInfoModel>>>() {
                }.getType();
                BaseResultEntity<List<FindCarInfoModel>> cacheList = gson.fromJson(cache, type);
                setViewPageData(cacheList.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) getContext(), "1");
        findCarInfoApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        findCarInfoApi.setPage("1");
        findCarInfoApi.setSize("5");
        findCarInfoApi.setTitle("");
        findCarInfoApi.setShowInBanner("true");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(findCarInfoApi);
    }

    private List<FindCarInfoModel> findCarInfoModelList = new ArrayList<>();
    private void setViewPageData(List<FindCarInfoModel> list) {
        findCarInfoModelList.clear();
        findCarInfoModelList.addAll(list);
        ArrayList<String> imageUrlList  = new ArrayList<>();
        ArrayList<String> subTitleList = new ArrayList<>();
        for (FindCarInfoModel model : list){
            imageUrlList.add(model.getHomePageUrl());
            subTitleList.add(model.getSubTitle());
        }
        headBannerFind.setImageResources(imageUrlList, subTitleList, mAdCycleViewListener);
    }

    /***
     * 获取场景攻略数据
     */
    private void getStrategyList() {
        StrategyApi strategyApi = new StrategyApi(new HttpOnNextListener<List<FindStrategyModel>>() {
            @Override
            public void onNext(List<FindStrategyModel> list) {
                setStrategyList(list);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<FindStrategyModel>>>() {
                }.getType();
                BaseResultEntity<List<FindStrategyModel>> cacheList = gson.fromJson(cache, type);
                setStrategyList(cacheList.getData());

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) (getContext()));
        strategyApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(strategyApi);
    }


    private void setStrategyList(List<FindStrategyModel> list) {
        recycleViewStrategy.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recycleViewStrategy.setAdapter(findStrategyAdapter = new FindStrategyAdapter(getActivity()));
        if (itemDecoration == null) {
            itemDecoration = new SpaceDecoration((int) EasyRecycleViewUtils.convertDpToPixel(7.28f, getActivity()));
            recycleViewStrategy.addItemDecoration(itemDecoration);
        }
        findStrategyAdapter.addAll(list);
        findStrategyAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<FindStrategyModel>() {
            @Override
            public void onItemClick(View view, int position, FindStrategyModel model) {
                if (PhoneUtils.isNetworkConnected(getActivity())) {
                    Intent ti = new Intent(getActivity(), StrategyActivity.class);
                    ti.putExtra("model", model);
                    startActivity(ti);
                }

            }
        });
    }




    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //加载更多
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    carInformationAdapter.pauseMore();
                    recyclerViewNews.showError();
                    return;
                }
                page++;
            getDataList();

            }
        }, 1000);
    }

//    @Subscribe(code = Constants.COLLECTION, threadMode = ThreadMode.MAIN)
//    public void collection(CommonEvent event) {
//        getViewPageData();
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        stopImageTimerTask();
    }

    private ImageCycleView.ImageCycleViewListener mAdCycleViewListener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void onImageClick(int position, View imageView) {

            FindCarInfoModel model = findCarInfoModelList.get(position);
            Intent ti = new Intent(getContext(), InformationDetailActivity.class);
            ti.putExtra("title", model.getTitle());
            ti.putExtra("content", model.getContent());
            ti.putExtra("imgUrl", model.getCoverUrl());
            ti.putExtra("infoId", model.getInfoId());
            ti.putExtra("isCollect",model.isCollect());
            ti.putExtra("collectType","carInfo");
//                ti.putExtra("findCarInfoModel", model);
            getActivity().startActivity(ti);
        }

        @Override
        public void displayImage(String imageURL, ImageView imageView) {
            GlideUtils.loadImage(getActivity(), imageURL, imageView, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.default_banner, R.mipmap.default_banner);

        }
    };
}
